//
//  PopWebView.m
//  KidReading
//
//  Created by telen on 15/1/13.
//  Copyright (c) 2015年 刘赞黄Telen. All rights reserved.
//

#import "PopWebView.h"
#import "ConstDefine.h"

#define TopH_webbar 80
#define TopW_webbtn 80

@interface UIApplication (PopWebView)
- (void)popWebView:(NSDictionary*)dict;
@end

@implementation UIApplication (PopWebView)
- (void)popWebView:(NSDictionary *)dict
{
    NSData* responseData = [dict objectForKey:@"data"];
    NSString* URLString = [dict objectForKey:@"url"];
    AppDelegate* appdelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    PopWebView* webview = [[PopWebView alloc] initWithFrame:appdelegate.window.bounds];
    [webview.webview loadData:responseData MIMEType:@"text/html" textEncodingName:@"UTF-8"  baseURL:[NSURL URLWithString:URLString]];
    webview.labelUrl.text = URLString;
    [appdelegate.window addSubview:webview];
    [webview autoLayOut];
}
@end

@implementation PopWebView
{
    UIButton* btn;
    UIButton* safariBtn;
    UIActivityIndicatorView* loading;
}


+ (void)popWebViewWithData:(NSData *)responseData withURL:(NSString *)URLString
{
    [[UIApplication sharedApplication] performSelectorOnMainThread:@selector(popWebView:) withObject:@{@"data":responseData,@"url":URLString} waitUntilDone:NO];
}

- (void)dealloc
{
    self.webview = nil;
    _labelUrl = nil;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        //
        _labelUrl = [[UILabel alloc] initWithFrame:frame];
        [self addSubview:_labelUrl];
        _labelUrl.translatesAutoresizingMaskIntoConstraints = NO;
        _labelUrl.numberOfLines = 0;
        [_labelUrl lyt_alignLeftToParent];
        [_labelUrl lyt_alignRightToParentWithMargin:TopW_webbtn*2];
        [_labelUrl lyt_alignTopToParent];
        [_labelUrl lyt_setHeight:TopH_webbar];
        _labelUrl.text = @"url:";
        //
        btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [btn setTitle:@"Safari" forState:UIControlStateNormal];
        [self addSubview:btn];
        btn.translatesAutoresizingMaskIntoConstraints = NO;
        [btn lyt_alignTopToParent];
        [btn lyt_alignRightToParentWithMargin:TopW_webbtn];
        [btn lyt_setSize:CGSizeMake(TopW_webbtn, TopH_webbar)];
        [btn addTarget:self action:@selector(tosafari) forControlEvents:UIControlEventTouchUpInside];
        safariBtn = btn;
        //
        btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [btn setTitle:@"关闭" forState:UIControlStateNormal];
        [self addSubview:btn];
        btn.translatesAutoresizingMaskIntoConstraints = NO;
        [btn lyt_alignTopToParent];
        [btn lyt_alignRightToParent];
        [btn lyt_setSize:CGSizeMake(TopW_webbtn, TopH_webbar)];
        [btn addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
        //
        frame.size.height -= TopH_webbar;
        self.webview = [[UIWebView alloc] init];
        self.webview.mediaPlaybackRequiresUserAction = NO;
        self.webview.allowsInlineMediaPlayback = YES;
        //self.webview.scalesPageToFit = YES;
        self.clear_Bg = NO;
        _webview.scrollView.pagingEnabled = YES;
        [self addSubview:_webview];
        _webview.translatesAutoresizingMaskIntoConstraints = NO;
        [_webview lyt_alignTopToParentWithMargin:TopH_webbar];
        [_webview lyt_alignLeftToParent];
        [_webview lyt_alignRightToParent];
        [_webview lyt_alignBottomToParent];
        //
        _webview.delegate = self;
    }
    return self;
}

- (void)setClear_Bg:(BOOL)clear_Bg
{
    _clear_Bg = clear_Bg;
    if (clear_Bg) {
        [_webview setOpaque:NO];
        _webview.backgroundColor = [UIColor clearColor];
        _webview.paginationMode = UIWebPaginationModeUnpaginated;
        self.backgroundColor = [UIColor clearColor];
    }else{
        [_webview setOpaque:YES];
        _webview.backgroundColor = [UIColor clearColor];
        _webview.paginationMode = UIWebPaginationModeTopToBottom;//从上而下
        self.backgroundColor = [UIColor whiteColor];
    }
}

- (void)autoLayOut
{
    self.translatesAutoresizingMaskIntoConstraints = NO;
    [self lyt_alignToParentWithMargin:TopH_webbar];
}

- (void)autoLayOut_FullWebView
{
    self.translatesAutoresizingMaskIntoConstraints = NO;
    [self lyt_alignToParentWithMargin:0];
    for (NSLayoutConstraint* constraint in self.constraints) {
        if (constraint.firstItem == _webview
            && constraint.firstAttribute == NSLayoutAttributeTop) {
            constraint.constant = 0;
        }
    }
    if(_labelUrl)[_labelUrl removeFromSuperview],_labelUrl = nil;
    if(btn)[btn removeFromSuperview],btn = nil;
    if(safariBtn)[safariBtn removeFromSuperview],safariBtn = nil;
}

- (void)close
{
    [self removeFromSuperview];
}

- (void)tosafari
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_labelUrl.text]];
}

- (void)addWaittingView
{
    if (!loading) {
        loading = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    }
    loading.center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
    [loading startAnimating];
    [_webview addSubview:loading];
    //
    loading.translatesAutoresizingMaskIntoConstraints = NO;
    [loading lyt_centerInParent];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (_delegate && [_delegate respondsToSelector:@selector(popWebView:shouldStartLoadWithRequest:navigationType:)]) {
        return [_delegate popWebView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
    }
    //
    if(_isClickToBrower && navigationType == UIWebViewNavigationTypeLinkClicked){
        [[UIApplication sharedApplication] openURL:request.URL];
        return NO;
    }
    else
    {
        _labelUrl.text = [[request URL] absoluteString];
        [[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];
    }
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [self addWaittingView];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [loading removeFromSuperview];
    if (_claar_DeviceWith) {
        [self reg_poptool_js];
        [self js_poptool_clean_device_width];
        //
        //[self log_AllHtml];
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [loading removeFromSuperview];
}

#pragma mark- privte
- (void)reg_poptool_js
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"poptool" ofType:@"js"];
    NSString *jsString = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    if (jsString) {
        [_webview stringByEvaluatingJavaScriptFromString:jsString];
    }else{
        NSLog(@"poptool.js Error");
    }
}

- (void)js_poptool_clean_device_width
{
    NSString * strJS = @"clean_device_width()";
    NSString * jsRestult = [_webview stringByEvaluatingJavaScriptFromString:strJS];
    if ([@"true" isEqualToString:jsRestult]) {
        strJS = @"update_tag_attr_src(\"meta\",\"content\",\"\",\"width=50%\")";
        jsRestult = [_webview stringByEvaluatingJavaScriptFromString:strJS];
    }
    //NSLog(@"%@",jsRestult);
}

- (void)log_AllHtml
{
    NSString *lJs = @"document.documentElement.innerHTML";
    NSString *lHtml = [_webview stringByEvaluatingJavaScriptFromString:lJs];
    NSLog(@"%@",lHtml);
}

@end

/*
 
 - (void)getjustPageWidth {
 NSString * strJS = @"document.getElementsByTagName(\"meta\")[1].content";
 NSString * jsRestult = [_webview stringByEvaluatingJavaScriptFromString:strJS];
 NSLog(@"%@",jsRestult);
 }
 
- (void)adjustPage_noscale_1_Width:(UIWebView *)webView_ {
    
    NSString *widthStr = [NSString stringWithFormat:@"%f",webView_.frame.size.width];
    NSString * strJS = [NSString stringWithFormat:@"function adjustPageWidth(){var metas = document.getElementsByTagName(\"meta\");var strMeta=new String();var strTemp;for(var i=0;i < metas.length;i++){if(metas[i].name == \"viewport\"){metas[i].setAttribute('content',\"width=%@, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\");console.log(metas[i].name);}}}",widthStr];
    [webView_ stringByEvaluatingJavaScriptFromString:strJS];
    NSString * strFunctionJS= @"adjustPageWidth();";
    [webView_ stringByEvaluatingJavaScriptFromString:strFunctionJS];
    
}
 */
